import "../css/pagination.css";
import { useState } from "react";

export default function Pagination({ currentPage, totalPages, onPageChange }) {
  // const [showDropdown, setShowDropdown] = useState(false);

  //分页操作
  const handlePageClick = (page) => {
    // setShowDropdown(false);
    if (page === "next") {
      onPageChange(Math.min(currentPage + 1, totalPages));
    } else if (page === "prev") {
      onPageChange(Math.max(currentPage - 1, 1));
    } else {
      onPageChange(page); //回调函数，跳转到点击的页码
    }
  };

  //计算分页数
  const calculatePageNumbers = () => {
    const pages = [];
    const maxVisiblePages = 5; //页面只显示5页
    let startPage, endPage; //开始和结束的页码

    //如果总页数小于最大显示页数，即5，则显示出所有页码
    if (totalPages <= maxVisiblePages) {
      startPage = 1;
      endPage = totalPages;
    } else if (currentPage <= Math.floor(maxVisiblePages / 2)) {
      startPage = 1;
      endPage = maxVisiblePages;
    } else if (currentPage + Math.floor(maxVisiblePages / 2) >= totalPages) {
      startPage = totalPages - maxVisiblePages + 1;
      endPage = totalPages;
    } else {
      startPage = currentPage - Math.floor(maxVisiblePages / 2);
      endPage = currentPage + Math.floor(maxVisiblePages / 2);
    }
    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }
    return pages;
  };

  const pageNumbers = calculatePageNumbers(); //页码数

  if (totalPages > 0) {
    return (
      <div className="pagination">
        {/* 上一页 */}
        <button
          onClick={() => handlePageClick("prev")}
          disabled={currentPage === 1}
        >
          上一页
        </button>

        {/* 页数 */}
        {pageNumbers.map((page) => (
          <span
            key={page}
            className={page === currentPage ? "current-page" : ""}
            onClick={() => handlePageClick(page)}
          >
            第{page}页
          </span>
        ))}

        {/* 下一页 */}
        <button
          onClick={() => handlePageClick("next")}
          disabled={currentPage === totalPages}
        >
          下一页
        </button>
      </div>
    );
  } else {
    // 当totalPages=0时，不显示分页按钮
    return null;
  }
}
